package bankapplication.com.acme.bankapp.service.bank;

import bankapplication.com.acme.bankapp.domain.bank.*;

public class EmailService {
  private Thread emailparserthread;
  private final Queue<Email> emailqueue;
  
  public EmailService(){
    emailqueue = new Queue<Email>();
    emailparserthread = new Thread(new EmailQueueParser(emailqueue));
    emailparserthread.start();
  }
  
  public boolean sendNotificationEmail(Client client, String emailAddress){
    Email email = new Email(client, emailAddress);
    boolean result = emailqueue.add(email);
    if(!result){
      System.err.println("Cannot send an email : the service is closed;");
    }
    return result;
  }
  
  public void close() {
    final int closeattemptsamount = 5;
    final int delay = 1000;
    emailqueue.close();
    while(!emailqueue.isEmpty()){
      try{
        Thread.sleep(1000);
      }
      catch(InterruptedException e){
        e.printStackTrace();
      }
    }
    for(int i=0; i<closeattemptsamount; i++){
      if(emailparserthread.isAlive()){ 
        try{
          Thread.sleep(delay);
        }
        catch(InterruptedException e){
          e.printStackTrace();
          return;
        }
        emailparserthread.interrupt();
      }
    }
    if(emailparserthread.isAlive()){
      System.err.println("Cannot finish email thread.");
    }
  }
}
